package com.mayikt;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: maplefire
 * @Description: lock锁condition用法
 * @Date: 2022/09/01 20:27
 */
class Res3 {
    public String name;
    public String sex;

    public boolean flag = false; // false 可写不可读；true 可读不可写

    public Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();
}

class WriteThread3 extends Thread {

    private Res3 res;

    public WriteThread3(Res3 res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                res.lock.lock();
                if (res.flag) {
                    res.condition.await();
                }
                if (count == 0) {
                    res.name = "小明";
                    res.sex = "男";
                } else {
                    res.name = "小红";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                res.condition.signal();
            } catch (Exception e) {
            } finally {
                res.lock.unlock();
            }
        }
    }
}

class ReadThread3 extends Thread {

    private Res3 res;

    public ReadThread3(Res3 res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            try {
                res.lock.lock();
                if (!res.flag) {
                    res.condition.await();
                }
                System.out.println("姓名:" + res.name + ",性别:" + res.sex);
                res.flag = false;
                res.condition.signal();
            } catch (Exception e) {

            } finally {
                res.lock.unlock();
            }

        }
    }
}

public class Test03 {
    public static void main(String[] args) {
        Res3 res = new Res3();
        WriteThread3 writeThread = new WriteThread3(res);
        ReadThread3 readThread = new ReadThread3(res);
        writeThread.start();
        readThread.start();
    }
}
